package CourseDesign;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

public class MyReadWriteLock {
    static int readers = 0;
    static int writers = 0;
    static boolean writing = false;
    static ReentrantLock mutex = new ReentrantLock();
    static ReentrantLock writeLock = new ReentrantLock();
    static Semaphore write = new Semaphore(1);
    static Random random = new Random();
    static void reader() {
        try {
            writeLock.lock();
            mutex.lock();
            readers++;
            if (readers == 1) {
                write.acquire();
            }
            mutex.unlock();
            writeLock.unlock();
            System.out.println(Thread.currentThread().getName()+" 正在读书，当前读者共有 " + readers);
            Thread.sleep(random.nextInt(200)); // Simulate reading time

            mutex.lock();
            readers--;
            System.out.println(Thread.currentThread().getName()+" 读书完成，当前读者共有 " + readers);
            if (readers == 0) {
                write.release();
            }
            mutex.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static void writer() throws InterruptedException {
        writeLock.lock();
        write.acquire();
        System.out.println(Thread.currentThread().getName()+"正在写入");
        Thread.sleep(random.nextInt(10));
        write.release();
        writeLock.unlock();
    }
}
